package com.bowen.controller;

import com.bowen.entity.Student;
import com.bowen.service.StudentService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangbw on 2018/11/22
 * Describe：服务提供者-学生信息控制器
 */
@RestController
@RequestMapping("/student")
public class StudentProviderController {

    @Resource
    private StudentService studentService;

    /**
     * 添加或者修改学生信息
     * @param student
     * @return
     */
    @PostMapping(value="/save")
    public boolean save(@RequestBody Student student){
        try{
            System.out.println("save------1004");
            studentService.save(student);
            return true;
        }catch(Exception e){
            return false;
        }
    }

    /**
     * 查询学生信息
     * @return
     */
    @GetMapping(value="/list")
    public List<Student> list(){
        System.out.println("list------1004");
        return studentService.list();
    }

    /**
     * 根据id查询学生信息
     * @return
     */
    @GetMapping(value="/get/{id}")
    public Student get(@PathVariable("id") Integer id){
        System.out.println("get------1004");
        return studentService.findById(id);
    }

    /**
     * 根据id删除学生信息
     * @return
     */
    @GetMapping(value="/delete/{id}")
    public boolean delete(@PathVariable("id") Integer id){
        try{
            System.out.println("delete------1004");
            studentService.delete(id);
            return true;
        }catch(Exception e){
            return false;
        }
    }

    /**
     * 1、获取信息，Hystrix测试（耦合度高）
     * @return
     * @throws InterruptedException
     */
    //    @ResponseBody
    //    @GetMapping(value="/getInfo")
    //    @HystrixCommand(fallbackMethod="getInfoFallback")
    //    public Map<String,Object> getInfo() throws InterruptedException{
    //        Thread.sleep(4000);  //模拟超时 hystrix默认1秒算超时
    //        Map<String,Object> map=new HashMap<String,Object>();
    //        map.put("code", 200);
    //        map.put("info", "业务数据xxxxx1004");
    //        return map;
    //    }
    //
    //    public Map<String,Object> getInfoFallback() throws InterruptedException{
    //        Map<String,Object> map=new HashMap<String,Object>();
    //        map.put("code", 500);
    //        map.put("info", "系统出错，稍后重试1004");
    //        return map;
    //    }

    /**
     * 2、获取信息，Feign Hystrix整合&服务熔断服务降级彻底解耦（耦合度低）
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping(value="/getInfo")
    public Map<String,Object> getInfo() throws InterruptedException{
        Thread.sleep(3100);  //模拟超时 hystrix默认1秒算超时
        return studentService.getInfo();
    }
}
